<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';

import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

import FixedConsumptionModal from '../../inpatient/components/FixedConsumptionModal.vue';
import InpatientLogModal from '../../inpatient/components/InpatientLogModal.vue';

interface Props {
  pet?: any;
  inpatientData?: any;
  inpatientRecords?: any[];
}

interface Emits {
  (e: 'save', data: any): void;
  (e: 'addRecord', pet: any): void;
  (e: 'selectRecord', record: any): void;
  (e: 'addInpatientRecord', data: any): void;
  (e: 'editInpatientRecord', record: any): void;
  (e: 'getCustomerRecords', pet: any): void;
}

const props = withDefaults(defineProps<Props>(), {
  pet: () => ({}),
  inpatientData: () => ({}),
});

const emit = defineEmits<Emits>();

// 住院数据
const inpatientData = ref({
  admissionDate: null,
  conditionType: '',
  responsibleDoctor: '',
  dischargeMethod: 'manual',
  dischargeDate: null,
  remarks: '',
  ...props.inpatientData,
});

// 住院日志
const showLogModal = ref(false);
const showFixedConsumptionModal = ref(false);
const inpatientLogs = ref([]);
const selectedRecordId = ref('');
const inpatientRecords = ref(props.inpatientRecords || []);

// 编辑日志相关状态
const isEditingLog = ref(false);
const editingLogId = ref('');

// 选择病历模态框
const showSelectRecordModal = ref(false);
const customerRecords = ref([]);
// 移除不再需要的selectedDay变量
const selectedRecord = ref(null);
const showPreviewModal = ref(false);
const previewRecord = ref(null);

// 暴露方法给父组件
const setCustomerRecords = (records: any[]) => {
  customerRecords.value = records;
};

defineExpose({
  setCustomerRecords,
});

// 表格列定义
const logColumns = [
  { title: '日期', dataIndex: 'date', key: 'date', width: 100 },
  { title: '打扫', dataIndex: 'cleaning', key: 'cleaning', width: 60 },
  { title: '装水', dataIndex: 'waterRefill', key: 'waterRefill', width: 60 },
  { title: '灌食', dataIndex: 'feeding', key: 'feeding', width: 60 },
  { title: '大便', dataIndex: 'defecation', key: 'defecation', width: 60 },
  { title: '小便', dataIndex: 'urination', key: 'urination', width: 60 },
  { title: '测体温', dataIndex: 'temperature', key: 'temperature', width: 80 },
  {
    title: '异常情况',
    dataIndex: 'abnormalConditions',
    key: 'abnormalConditions',
    width: 120,
  },
  {
    title: '护理记录',
    dataIndex: 'nursingRecords',
    key: 'nursingRecords',
    width: 120,
  },
  {
    title: '消费合计',
    dataIndex: 'consumption',
    key: 'consumption',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    fixed: 'right',
  },
];

// 计算入住时间
const stayDuration = computed(() => {
  if (!inpatientData.value.admissionDate) return 0;
  const admission = dayjs(inpatientData.value.admissionDate);
  const discharge =
    inpatientData.value.dischargeMethod === 'specified'
      ? dayjs(inpatientData.value.dischargeDate)
      : dayjs();
  return Math.max(1, discharge.diff(admission, 'day'));
});

// 计算是否已出院
const isDischarged = computed(() => {
  return inpatientData.value.status === 'discharged';
});

// 计算总消费
const totalConsumption = computed(() => {
  return inpatientLogs.value.reduce(
    (total, log) => total + (log.consumptionTotal || 0),
    0,
  );
});

// 监听住院数据变化
watch(
  inpatientData,
  (newData) => {
    emit('save', newData);
  },
  { deep: true },
);

// 监听props.inpatientData变化，更新本地数据
watch(
  () => props.inpatientData,
  (newInpatientData) => {
    if (newInpatientData && Object.keys(newInpatientData).length > 0) {
      // 更新本地住院数据
      Object.assign(inpatientData.value, newInpatientData);

      console.log('InpatientGroup: 接收到新的住院数据:', {
        id: newInpatientData.id,
        name: newInpatientData.inpatientName,
        status: newInpatientData.status,
      });
    }
  },
  { deep: true, immediate: true },
);

// 监听props.inpatientRecords变化
watch(
  () => props.inpatientRecords,
  (newRecords) => {
    if (newRecords) {
      inpatientRecords.value = [...newRecords];
      console.log('InpatientGroup: 接收到新的住院记录:', newRecords.length);
    }
  },
  { deep: true, immediate: true },
);

// 方法
const handlePrint = () => {
  console.log('打印住院信息');
};

const refreshLogs = () => {
  loadInpatientLogs();
};

// 编辑住院日志
const handleEditLog = (logRecord: any) => {
  console.log('编辑住院日志:', logRecord);

  // 设置编辑模式
  showLogModal.value = true;

  // 将日志数据填充到表单中
  Object.assign(formData.value, {
    date: logRecord.date ? dayjs(logRecord.date) : dayjs(),
    cleaning: logRecord.cleaning || false,
    waterRefill: logRecord.waterRefill || false,
    feeding: logRecord.feeding || false,
    defecation: logRecord.defecation || false,
    urination: logRecord.urination || false,
    temperature: logRecord.temperature || false,
    abnormalConditions: logRecord.abnormalConditions || '',
    nursingRecords: logRecord.nursingRecords || '',
    consumptionTotal: logRecord.consumptionTotal || 0,
  });

  // 标记为编辑模式
  isEditingLog.value = true;
  editingLogId.value = logRecord.id;
};

// 删除住院日志
const handleDeleteLog = (logRecord: any) => {
  if (confirm(`确定要删除 ${logRecord.date} 的住院日志记录吗？`)) {
    const index = inpatientLogs.value.findIndex(
      (log) => log.id === logRecord.id,
    );
    if (index !== -1) {
      inpatientLogs.value.splice(index, 1);

      // 保存更新后的日志
      emit('save', {
        ...inpatientData.value,
        logs: inpatientLogs.value,
        records: inpatientRecords.value,
      });

      message.success('住院日志删除成功！');
    }
  }
};

const handleLogSuccess = (logData: any) => {
  if (isEditingLog.value) {
    // 编辑模式：更新现有记录
    const index = inpatientLogs.value.findIndex(
      (log) => log.id === editingLogId.value,
    );
    if (index !== -1) {
      inpatientLogs.value[index] = {
        ...logData,
        id: editingLogId.value.valueidid,
      };
    }

    // 重置编辑状态
    isEditingLog.value = false;
    editingLogId.value = '';
    message.success('住院日志更新成功！');
  } else {
    // 新增模式：添加新记录
    inpatientLogs.value.push(logData);
    message.success('住院日志添加成功！');
  }

  showLogModal.value = false;

  // 保存到本地存储
  emit('save', {
    ...inpatientData.value,
    logs: inpatientLogs.value,
    records: inpatientRecords.value,
  });
};

const handleFixedConsumptionSuccess = (consumptionData: any) => {
  // 保存固定消费设置
  inpatientData.value.fixedConsumption = consumptionData;
  showFixedConsumptionModal.value = false;

  // 保存到本地存储
  emit('save', {
    ...inpatientData.value,
    logs: inpatientLogs.value,
    records: inpatientRecords.value,
  });

  message.success('固定消费设置成功！');
};

const handleAddInpatientRecord = () => {
  // 获取当前顾客的所有病历记录
  emit('getCustomerRecords', props.pet);

  // 显示选择病历模态框
  showSelectRecordModal.value = true;
};

// 移除不再需要的handleAddInpatientRecordForDay方法

// 获取病情分类的显示文本
const getConditionTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    surgery: '手术',
    treatment: '治疗',
    observation: '观察',
    emergency: '急诊',
  };
  return typeMap[type] || '未知';
};

// 格式化日期显示
const formatDate = (date: any) => {
  if (!date) return '';
  return dayjs(date).format('YYYY-MM-DD');
};

// 移除不再需要的天数相关方法

// 移除不再需要的getRecordsByDay方法

const handleEditRecord = (record: any) => {
  emit('editInpatientRecord', {
    pet: props.pet,
    inpatientData: inpatientData.value,
    record,
  });
};

const handleDeleteRecord = (record: any) => {
  // 确认删除
  if (confirm(`确定要删除住院病历 "${record.recordDate}" 吗？`)) {
    const index = inpatientRecords.value.findIndex((r) => r.id === record.id);
    if (index !== -1) {
      inpatientRecords.value.splice(index, 1);
    }
  }
};

// 处理选择病历
const handleSelectRecord = (record: any) => {
  selectedRecord.value = record;
};

// 预览病历详情
const handlePreviewRecord = (record: any) => {
  previewRecord.value = record;
  showPreviewModal.value = true;
};

// 关闭预览模态框
const handleClosePreview = () => {
  showPreviewModal.value = false;
  previewRecord.value = null;
};

// 预览住院病历
const handlePreviewInpatientRecord = (record: any) => {
  previewRecord.value = record;
  showPreviewModal.value = true;
};

// 确认选择病历
const handleConfirmSelectRecord = () => {
  if (!selectedRecord.value) {
    message.warning('请选择一个病历记录');
    return;
  }

  // 检查病历状态，草稿状态不允许添加
  if (selectedRecord.value.status === 'draft') {
    message.warning('草稿状态的病历不能添加到住院病历中，请先确认病历');
    return;
  }

  // 使用当前日期
  const recordDate = dayjs();

  // 创建新的住院病历记录（基于选择的病历）
  const newRecord = {
    id: `IR${Date.now()}`,
    recordDate: recordDate.format('YYYY-MM-DD'),
    recordTime: dayjs().format('HH:mm'),
    doctor:
      selectedRecord.value.doctor ||
      inpatientData.value.responsibleDoctor ||
      '',
    complaint:
      selectedRecord.value.chiefComplaint ||
      selectedRecord.value.complaint ||
      '',
    diagnosis: selectedRecord.value.diagnosis || '',
    examination: selectedRecord.value.examination || {
      earsEyesMouthNose: 'normal',
      bonesMuscles: 'normal',
      skinCoat: 'normal',
      lymphNodes: 'normal',
      heartLungs: 'normal',
      abdominalPalpation: 'normal',
    },
    labTests: selectedRecord.value.labTests || [],
    prescriptions: selectedRecord.value.prescriptions || [],
    surgeries: selectedRecord.value.surgeries || [],
    treatments: selectedRecord.value.treatments || [],
    doctorAdvice: selectedRecord.value.doctorAdvice || '',
    precautions: selectedRecord.value.precautions || '',
    status: 'confirmed', // 保持原病历的状态;
    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    sourceRecordId: selectedRecord.value.id, // 记录来源病历ID
  };

  // 直接添加到住院病历列表，不跳转到病历详情
  inpatientRecords.value.unshift(newRecord);

  // 关闭模态框并重置状态
  showSelectRecordModal.value = false;
  selectedRecord.value = null;

  message.success('住院病历添加成功！');
};

// 创建空白病历
const handleCreateBlankRecord = () => {
  // 使用当前日期
  const recordDate = dayjs();

  // 创建新的空白住院病历记录
  const newRecord = {
    id: `IR${Date.now()}`,
    recordDate: recordDate.format('YYYY-MM-DD'),
    recordTime: dayjs().format('HH:mm'),
    doctor: inpatientData.value.responsibleDoctor || '',
    complaint: '',
    diagnosis: '',
    examination: {
      earsEyesMouthNose: 'normal',
      bonesMuscles: 'normal',
      skinCoat: 'normal',
      lymphNodes: 'normal',
      heartLungs: 'normal',
      abdominalPalpation: 'normal',
    },
    labTests: [],
    prescriptions: [],
    surgeries: [],
    treatments: [],
    doctorAdvice: '',
    precautions: '',
    status: 'draft',
    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  };

  emit('addInpatientRecord', {
    pet: props.pet,
    inpatientData: inpatientData.value,
    record: newRecord,
  });

  // 关闭模态框
  showSelectRecordModal.value = false;
};

const selectRecord = (record: any) => {
  // 清除之前的选择
  selectedRecordId.value = '';

  // 设置新的选择
  selectedRecordId.value = record.id;

  // 调试信息
  console.log('选择住院病历:', {
    recordId: record.id,
    recordDate: record.recordDate,
    inpatientDay: record.inpatientDay,
    selectedRecordId: selectedRecordId.value,
  });

  emit('selectRecord', record);
};

const handleSave = () => {
  emit('save', {
    ...inpatientData.value,
    logs: inpatientLogs.value,
    records: inpatientRecords.value,
  });
};

// 办理出院
const handleDischarge = () => {
  if (confirm('确定要办理出院吗？出院后将无法修改住院信息和病历记录。')) {
    // 更新住院状态为已出院
    inpatientData.value.status = 'discharged';

    // 更新所有住院病历状态为已存档
    inpatientRecords.value.forEach((record) => {
      record.status = 'archived';
    });

    // 保存出院状态
    emit('save', {
      ...inpatientData.value,
      logs: inpatientLogs.value,
      records: inpatientRecords.value,
    });

    message.success('出院办理成功！');
  }
};

// 加载住院日志
const loadInpatientLogs = () => {
  // 模拟数据
  inpatientLogs.value = [
    {
      id: '1',
      date: '2024-01-15',
      cleaning: true,
      waterRefill: true,
      feeding: true,
      defecation: true,
      urination: true,
      temperature: true,
      abnormalConditions: '无',
      nursingRecords: '正常护理，宠物状态良好',
      consumptionTotal: 150,
    },
    {
      id: '2',
      date: '2024-01-16',
      cleaning: true,
      waterRefill: true,
      feeding: true,
      defecation: false,
      urination: true,
      temperature: true,
      abnormalConditions: '食欲稍差',
      nursingRecords: '加强营养，观察食欲变化',
      consumptionTotal: 180,
    },
    {
      id: '3',
      date: '2024-01-17',
      cleaning: true,
      waterRefill: true,
      feeding: true,
      defecation: true,
      urination: true,
      temperature: true,
      abnormalConditions: '无',
      nursingRecords: '恢复良好，可以准备出院',
      consumptionTotal: 120,
    },
  ];
};

// 加载住院病历
const loadInpatientRecords = () => {
  // 模拟数据
  inpatientRecords.value = [
    {
      id: `IR001_${Date.now()}`,
      recordDate: '2024-01-15',
      recordTime: '09:30',
      diagnosis: '感冒',
      doctor: '孙医生',
      status: 'confirmed',
    },
    {
      id: `IR002_${Date.now() + 1}`,
      recordDate: '2024-01-16',
      recordTime: '14:20',
      diagnosis: '发烧',
      doctor: '李医生',
      status: 'confirmed',
    },
    {
      id: `IR003_${Date.now() + 2}`,
      recordDate: '2024-01-17',
      recordTime: '10:15',
      diagnosis: '咳嗽',
      doctor: '王医生',
      status: 'draft',
    },
  ];

  // 调试信息
  console.log(
    '加载的住院病历数据:',
    inpatientRecords.value.map((r) => ({
      id: r.id,
      diagnosis: r.diagnosis,
      status: r.status,
    })),
  );
};

onMounted(() => {
  loadInpatientLogs();
  loadInpatientRecords();

  // 调试信息：检查所有记录的状态
  console.log('组件挂载完成，检查住院记录状态:');
  console.log('selectedRecordId:', selectedRecordId.value);
  console.log(
    'inpatientRecords:',
    inpatientRecords.value.map((r) => ({
      id: r.id,
      diagnosis: r.diagnosis,
      inpatientDay: r.inpatientDay,
    })),
  );

  // 检查每个记录的选择状态
  inpatientRecords.value.forEach((record) => {
    console.log(
      `记录 ${record.id} 的选择状态:`,
      selectedRecordId.value === record.id,
    );
  });
});
</script>

<template>
  <div class="inpatient-group">
    <!-- 住院组信息 -->
    <div class="inpatient-info">
      <div class="section-header">
        <h3>住院组</h3>
        <a-button type="text" size="small" @click="handlePrint">
          🖨️ 打印
        </a-button>
      </div>

      <a-form :model="inpatientData" layout="vertical" class="inpatient-form">
        <!-- 出院状态提示 -->
        <div v-if="isDischarged" class="discharge-notice">
          <a-alert
            message="已出院状态"
            description="该住院组已出院，住院信息和病历记录不可修改"
            type="warning"
            show-icon
            :closable="false"
          />
        </div>

        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="入院日期">
              <a-date-picker
                v-model:value="inpatientData.admissionDate"
                style="width: 100%"
                placeholder="选择入院日期"
                :disabled="isDischarged"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="住院名字">
              <a-input
                v-model:value="inpatientData.inpatientName"
                placeholder="请输入住院名字（方便记忆住院原因）"
                style="width: 100%"
                :disabled="isDischarged"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="责任医生">
              <a-select
                v-model:value="inpatientData.responsibleDoctor"
                placeholder="选择责任医生"
                style="width: 100%"
                :disabled="isDischarged"
              >
                <a-select-option value="doctor1">孙医生</a-select-option>
                <a-select-option value="doctor2">李医生</a-select-option>
                <a-select-option value="doctor3">王医生</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="病情分类">
              <a-select
                v-model:value="inpatientData.conditionType"
                placeholder="选择病情分类"
                style="width: 100%"
                :disabled="isDischarged"
              >
                <a-select-option value="surgery">手术</a-select-option>
                <a-select-option value="treatment">治疗</a-select-option>
                <a-select-option value="observation">观察</a-select-option>
                <a-select-option value="emergency">急诊</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 出院方式 -->
        <a-form-item label="出院方式">
          <a-radio-group
            v-model:value="inpatientData.dischargeMethod"
            :disabled="isDischarged"
          >
            <a-radio value="manual">手动办理出院，自动递增入住时间</a-radio>
            <a-radio value="specified">指定出院日期</a-radio>
          </a-radio-group>
          <div
            v-if="inpatientData.dischargeMethod === 'specified'"
            style="margin-top: 8px"
          >
            <a-date-picker
              v-model:value="inpatientData.dischargeDate"
              placeholder="选择出院日期"
              :disabled="isDischarged"
            />
          </div>
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="入住时间">
              <span class="stay-duration">{{ stayDuration }}天</span>
            </a-form-item>
          </a-col>
          <a-col :span="16">
            <a-form-item label="备注">
              <a-input
                v-model:value="inpatientData.remarks"
                placeholder="请输入备注信息"
                :disabled="isDischarged"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 住院日志 -->
    <div class="inpatient-log">
      <div class="section-header">
        <h3>住院日志</h3>
        <div class="log-actions">
          <span class="total-consumption"
            >住院期间总消费: ¥{{ totalConsumption.toFixed(2) }}</span
          >
          <a-button type="primary" size="small" @click="showLogModal = true">
            + 添加记录
          </a-button>
        </div>
      </div>

      <div v-if="inpatientLogs.length === 0" class="empty-log">
        <p>若没今日数据，请点击刷新</p>
        <a-button type="link" @click="refreshLogs">刷新</a-button>
      </div>

      <a-table
        v-else
        :columns="logColumns"
        :data-source="inpatientLogs"
        :pagination="false"
        size="small"
        class="log-table"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'cleaning'">
            <a-tag v-if="record.cleaning" color="green">✓</a-tag>
            <a-tag v-else color="red">✗</a-tag>
          </template>
          <template v-else-if="column.key === 'waterRefill'">
            <a-tag v-if="record.waterRefill" color="green">✓</a-tag>
            <a-tag v-else color="red">✗</a-tag>
          </template>
          <template v-else-if="column.key === 'feeding'">
            <a-tag v-if="record.feeding" color="green">✓</a-tag>
            <a-tag v-else color="red">✗</a-tag>
          </template>
          <template v-else-if="column.key === 'defecation'">
            <a-tag v-if="record.defecation" color="green">✓</a-tag>
            <a-tag v-else color="red">✗</a-tag>
          </template>
          <template v-else-if="column.key === 'urination'">
            <a-tag v-if="record.urination" color="green">✓</a-tag>
            <a-tag v-else color="red">✗</a-tag>
          </template>
          <template v-else-if="column.key === 'temperature'">
            <a-tag v-if="record.temperature" color="green">✓</a-tag>
            <a-tag v-else color="red">✗</a-tag>
          </template>
          <template v-else-if="column.key === 'consumption'">
            ¥{{ record.consumptionTotal.toFixed(2) }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button
                type="text"
                size="small"
                @click="handleEditLog(record)"
                :disabled="isDischarged"
              >
                ✏️ 编辑
              </a-button>
              <a-button
                type="text"
                size="small"
                danger
                @click="handleDeleteLog(record)"
                :disabled="isDischarged"
              >
                🗑️ 删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 每日固定消费 -->
    <div class="fixed-consumption">
      <div class="section-header">
        <h3>每日固定消费</h3>
        <a-button
          type="primary"
          size="small"
          @click="showFixedConsumptionModal = true"
        >
          {{ inpatientData.fixedConsumption ? '修改' : '设置' }}
        </a-button>
      </div>

      <div v-if="inpatientData.fixedConsumption" class="fixed-consumption-info">
        <div class="consumption-items">
          <div
            v-for="item in inpatientData.fixedConsumption.items"
            :key="item.id"
            class="consumption-item"
          >
            <span class="item-name">{{ item.name }}</span>
            <span class="item-quantity">×{{ item.quantity }}</span>
            <span class="item-price">¥{{ item.price }}</span>
            <span class="item-total"
              >¥{{ (item.price * item.quantity).toFixed(2) }}</span
            >
          </div>
        </div>
        <div class="consumption-total">
          <span class="total-label">每日固定消费：</span>
          <span class="total-amount"
            >¥{{
              inpatientData.fixedConsumption.totalDailyAmount.toFixed(2)
            }}</span
          >
        </div>
      </div>

      <div v-else class="no-fixed-consumption">
        <a-button type="dashed" block @click="showFixedConsumptionModal = true">
          + 设置每日固定消费
        </a-button>
        <p class="consumption-tip">添加每日固定消费，住院期间自动生成</p>
      </div>
    </div>

    <!-- 住院病历管理 -->
    <div class="inpatient-medical-records">
      <div class="section-header">
        <h3>住院病历管理</h3>
        <div class="debug-info" style="font-size: 12px; color: #999">
          当前选中: {{ selectedRecordId || '无' }}
        </div>
      </div>

      <!-- 住院记录列表 -->
      <div class="inpatient-records-list">
        <!-- 住院组标题 -->
        <div class="inpatient-group-title">
          <span class="condition-type">{{
            getConditionTypeText(inpatientData.conditionType)
          }}</span>
          <span class="admission-date"
            >入院: {{ formatDate(inpatientData.admissionDate) }}</span
          >
          <div class="inpatient-name" v-if="inpatientData.inpatientName">
            <span class="name-label">🏥 {{ inpatientData.inpatientName }}</span>
          </div>
        </div>

        <!-- 住院记录列表 -->
        <div class="records-container">
          <div
            v-for="record in inpatientRecords"
            :key="record.id"
            class="record-item"
            :class="{ active: selectedRecordId === record.id }"
            @click="selectRecord(record)"
            :title="`ID: ${record.id}, 选中状态: ${selectedRecordId === record.id}`"
          >
            <div class="record-info">
              <span class="record-time">{{ record.recordTime || '' }}</span>
              <span class="record-status" :class="record.status">
                {{ record.status === 'draft' ? '📝 草稿' : '✅ 已确认' }}
              </span>
            </div>
            <div class="record-summary">
              <span class="diagnosis">{{
                record.diagnosis || '暂无诊断'
              }}</span>
              <span class="doctor">{{ record.doctor }}</span>
            </div>
            <div class="record-actions">
              <a-button
                type="text"
                size="small"
                @click.stop="handlePreviewInpatientRecord(record)"
              >
                👁️ 预览
              </a-button>
              <a-button
                v-if="!isDischarged"
                type="text"
                size="small"
                @click.stop="handleEditRecord(record)"
              >
                ✏️ 编辑
              </a-button>
              <a-button
                v-if="record.status === 'draft' && !isDischarged"
                type="text"
                size="small"
                danger
                @click.stop="handleDeleteRecord(record)"
              >
                🗑️ 删除
              </a-button>
              <span
                v-if="isDischarged && record.status === 'archived'"
                class="archived-tag"
              >
                📁 已存档
              </span>
            </div>
          </div>

          <!-- 添加住院病历按钮 -->
          <div class="add-record-button">
            <a-button
              v-if="!isDischarged"
              type="dashed"
              size="small"
              @click="handleAddInpatientRecord"
            >
              + 添加住院病历
            </a-button>
            <div v-else class="disabled-add-button">
              <span class="disabled-text">已出院，无法添加病历</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 保存按钮 -->
    <div class="save-actions">
      <a-button
        v-if="!isDischarged"
        type="primary"
        size="large"
        @click="handleSave"
      >
        保存
      </a-button>
      <a-button
        v-if="!isDischarged"
        type="danger"
        size="large"
        @click="handleDischarge"
        style="margin-left: 16px"
      >
        办理出院
      </a-button>
      <div v-if="isDischarged" class="discharged-notice">
        <a-tag color="green" size="large">✅ 已出院</a-tag>
      </div>
    </div>

    <!-- 住院日志模态框 -->
    <InpatientLogModal
      :visible="showLogModal"
      :pet="pet"
      :is-edit="isEditingLog"
      :edit-data="isEditingLog ? formData : null"
      @update:visible="showLogModal = $event"
      @success="handleLogSuccess"
    />

    <!-- 固定消费模态框 -->
    <FixedConsumptionModal
      :visible="showFixedConsumptionModal"
      :pet="pet"
      @update:visible="showFixedConsumptionModal = $event"
      @success="handleFixedConsumptionSuccess"
    />

    <!-- 选择病历模态框 -->
    <a-modal
      :visible="showSelectRecordModal"
      title="选择病历记录"
      width="800px"
      @cancel="showSelectRecordModal = false"
      :footer="null"
    >
      <div class="select-record-modal">
        <div class="modal-header">
          <p class="modal-tip">
            为第 {{ selectedDay }} 天选择病历记录，您可以：
          </p>
          <div class="modal-actions">
            <a-button type="primary" @click="handleCreateBlankRecord">
              📝 创建空白病历
            </a-button>
          </div>
        </div>

        <div class="records-section">
          <h4>📋 选择已有病历记录（仅显示已确认的病历）</h4>
          <div v-if="customerRecords.length === 0" class="empty-records">
            <p>暂无病历记录</p>
          </div>
          <div v-else class="records-list">
            <div
              v-for="record in customerRecords.filter(
                (r) => r.status === 'confirmed',
              )"
              :key="record.id"
              class="record-item"
              :class="{ active: selectedRecord?.id === record.id }"
              @click="handleSelectRecord(record)"
            >
              <div class="record-header">
                <div class="record-info">
                  <span class="record-date">{{ record.recordDate }}</span>
                  <span class="record-number">{{ record.recordNumber }}</span>
                </div>
                <div class="record-status">
                  <span class="status-tag" :class="record.status">
                    {{ record.status === 'draft' ? '📝 草稿' : '✅ 已确认' }}
                  </span>
                </div>
              </div>
              <div class="record-content">
                <div class="record-main">
                  <span class="diagnosis">{{
                    record.diagnosis || '暂无诊断'
                  }}</span>
                  <span class="doctor">{{ record.doctor }}</span>
                </div>
                <div class="record-details">
                  <span class="complaint">{{
                    record.chiefComplaint || record.complaint || '暂无主诉'
                  }}</span>
                </div>
                <div class="record-actions">
                  <a-button
                    type="text"
                    size="small"
                    @click.stop="handlePreviewRecord(record)"
                  >
                    👁️ 预览
                  </a-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <a-button @click="showSelectRecordModal = false">取消</a-button>
          <a-button
            type="primary"
            :disabled="!selectedRecord"
            @click="handleConfirmSelectRecord"
          >
            确认选择
          </a-button>
        </div>
      </div>
    </a-modal>

    <!-- 病历预览模态框 -->
    <a-modal
      :visible="showPreviewModal"
      title="病历详情预览"
      width="900px"
      @cancel="handleClosePreview"
      :footer="null"
    >
      <div v-if="previewRecord" class="preview-modal">
        <div class="preview-header">
          <div class="record-basic-info">
            <h4>基本信息</h4>
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="病历日期">
                {{ previewRecord.recordDate }}
              </a-descriptions-item>
              <a-descriptions-item label="病历编号">
                {{ previewRecord.recordNumber }}
              </a-descriptions-item>
              <a-descriptions-item label="主治医生">
                {{ previewRecord.doctor }}
              </a-descriptions-item>
              <a-descriptions-item label="病历状态">
                <span class="status-tag" :class="previewRecord.status">
                  {{
                    previewRecord.status === 'draft' ? '📝 草稿' : '✅ 已确认'
                  }}
                </span>
              </a-descriptions-item>
            </a-descriptions>
          </div>
        </div>

        <div class="preview-content">
          <div class="preview-section">
            <h4>主诉</h4>
            <p>
              {{
                previewRecord.chiefComplaint ||
                previewRecord.complaint ||
                '暂无主诉'
              }}
            </p>
          </div>

          <div class="preview-section">
            <h4>诊断</h4>
            <p>{{ previewRecord.diagnosis || '暂无诊断' }}</p>
          </div>

          <div v-if="previewRecord.examination" class="preview-section">
            <h4>体格检查</h4>
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="耳眼口鼻">
                {{ previewRecord.examination.earsEyesMouthNose }}
              </a-descriptions-item>
              <a-descriptions-item label="骨骼肌肉">
                {{ previewRecord.examination.bonesMuscles }}
              </a-descriptions-item>
              <a-descriptions-item label="皮肤被毛">
                {{ previewRecord.examination.skinCoat }}
              </a-descriptions-item>
              <a-descriptions-item label="淋巴结">
                {{ previewRecord.examination.lymphNodes }}
              </a-descriptions-item>
              <a-descriptions-item label="心肺">
                {{ previewRecord.examination.heartLungs }}
              </a-descriptions-item>
              <a-descriptions-item label="腹部触诊">
                {{ previewRecord.examination.abdominalPalpation }}
              </a-descriptions-item>
            </a-descriptions>
          </div>

          <div
            v-if="previewRecord.labTests && previewRecord.labTests.length > 0"
            class="preview-section"
          >
            <h4>检验项目</h4>
            <a-table
              :columns="[
                { title: '项目名称', dataIndex: 'name', key: 'name' },
                { title: '价格', dataIndex: 'price', key: 'price' },
              ]"
              :data-source="previewRecord.labTests"
              :pagination="false"
              size="small"
            />
          </div>

          <div
            v-if="
              previewRecord.prescriptions &&
              previewRecord.prescriptions.length > 0
            "
            class="preview-section"
          >
            <h4>处方项目</h4>
            <a-table
              :columns="[
                { title: '名称', dataIndex: 'name', key: 'name' },
                {
                  title: '规格',
                  dataIndex: 'specification',
                  key: 'specification',
                },
                { title: '用法', dataIndex: 'usage', key: 'usage' },
                { title: '用量', dataIndex: 'dosage', key: 'dosage' },
              ]"
              :data-source="previewRecord.prescriptions"
              :pagination="false"
              size="small"
            />
          </div>

          <div v-if="previewRecord.doctorAdvice" class="preview-section">
            <h4>医嘱</h4>
            <p>{{ previewRecord.doctorAdvice }}</p>
          </div>

          <div v-if="previewRecord.precautions" class="preview-section">
            <h4>注意事项</h4>
            <p>{{ previewRecord.precautions }}</p>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<style scoped>
.inpatient-group {
  height: 100%;
  padding: 16px;
  overflow-y: auto;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 8px;
  margin-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  color: #1890ff;
}

.inpatient-form {
  margin-bottom: 24px;
}

.stay-duration {
  font-weight: bold;
  color: #1890ff;
}

.inpatient-log {
  margin-bottom: 24px;
}

.log-actions {
  display: flex;
  gap: 16px;
  align-items: center;
}

.total-consumption {
  font-weight: bold;
  color: #52c41a;
}

.empty-log {
  padding: 40px;
  color: #999;
  text-align: center;
}

.log-table {
  margin-top: 16px;
}

.fixed-consumption {
  margin-bottom: 24px;
}

.consumption-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
  text-align: center;
}

.inpatient-medical-records {
  margin-bottom: 24px;
}

.inpatient-records-list {
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.inpatient-group-title {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
  padding: 16px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.condition-type {
  font-size: 16px;
  font-weight: bold;
  color: #1890ff;
}

.admission-date {
  font-size: 14px;
  color: #666;
}

.inpatient-name {
  margin-left: auto;
}

.name-label {
  padding: 4px 8px;
  font-size: 12px;
  font-weight: 500;
  color: #1890ff;
  background: #e6f7ff;
  border-radius: 4px;
}

.records-container {
  max-height: 400px;
  padding: 16px;
  overflow-y: auto;
}

.record-item {
  padding: 12px;
  margin-bottom: 12px;
  cursor: pointer;
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  transition: all 0.3s;
}

.record-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgb(24 144 255 / 10%);
}

.record-item.active {
  background: #e6f7ff;
  border-color: #1890ff;
}

.record-item:last-child {
  margin-bottom: 0;
}

.record-item .record-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.record-item .record-time {
  font-size: 12px;
  color: #666;
}

.record-item .record-status {
  padding: 2px 6px;
  font-size: 12px;
  border-radius: 4px;
}

.record-item .record-status.draft {
  color: #fa8c16;
  background-color: #fff7e6;
}

.record-item .record-status.confirmed {
  color: #52c41a;
  background-color: #f6ffed;
}

.record-item .record-summary {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.record-item .diagnosis {
  font-weight: 500;
  color: #333;
}

.record-item .doctor {
  color: #666;
}

.record-item .record-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.add-record-button {
  margin-top: 12px;
  text-align: center;
}

.add-record-button .ant-btn {
  color: #1890ff;
  border-style: dashed;
}

.add-record-button .ant-btn:hover {
  color: #1890ff;
  border-color: #1890ff;
}

/* 选择病历模态框样式 */
.select-record-modal {
  padding: 16px 0;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 16px;
  margin-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-tip {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.modal-actions {
  display: flex;
  gap: 12px;
}

.records-section {
  margin-bottom: 24px;
}

.records-section h4 {
  margin-bottom: 16px;
  font-size: 16px;
  color: #333;
}

.records-section .records-list {
  max-height: 400px;
  overflow-y: auto;
}

.records-section .record-item {
  padding: 16px;
  margin-bottom: 12px;
  cursor: pointer;
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  transition: all 0.3s;
}

.records-section .record-item:hover {
  background: #f6ffed;
  border-color: #1890ff;
}

.records-section .record-item.active {
  background: #e6f7ff;
  border-color: #1890ff;
}

.records-section .record-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.records-section .record-info {
  display: flex;
  gap: 12px;
  align-items: center;
}

.records-section .record-date {
  font-weight: bold;
  color: #1890ff;
}

.records-section .record-number {
  padding: 2px 6px;
  font-size: 12px;
  color: #666;
  background: #f5f5f5;
  border-radius: 4px;
}

.records-section .status-tag {
  padding: 2px 6px;
  font-size: 12px;
  border-radius: 4px;
}

.records-section .status-tag.draft {
  color: #fa8c16;
  background-color: #fff7e6;
}

.records-section .status-tag.confirmed {
  color: #52c41a;
  background-color: #f6ffed;
}

.records-section .record-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.records-section .record-main {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
}

.records-section .diagnosis {
  font-weight: 500;
  color: #333;
}

.records-section .doctor {
  color: #666;
}

.records-section .record-details {
  font-size: 12px;
  color: #666;
}

.records-section .complaint {
  font-style: italic;
}

.modal-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

/* 预览模态框样式 */
.preview-modal {
  padding: 16px 0;
}

.preview-header {
  margin-bottom: 24px;
}

.preview-header h4 {
  margin-bottom: 16px;
  font-size: 16px;
  color: #333;
}

.preview-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.preview-section {
  padding: 16px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.preview-section h4 {
  margin-bottom: 12px;
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.preview-section p {
  margin: 0;
  line-height: 1.6;
  color: #666;
}

.save-actions {
  padding: 16px 0;
  text-align: center;
  border-top: 1px solid #f0f0f0;
}

.discharge-notice {
  margin-bottom: 16px;
}

.discharged-notice {
  display: flex;
  align-items: center;
  justify-content: center;
}

.archived-tag {
  padding: 2px 6px;
  font-size: 12px;
  color: #52c41a;
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 4px;
}

.disabled-add-button {
  padding: 8px 12px;
  text-align: center;
  background: #fafafa;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}

.disabled-text {
  font-size: 12px;
  color: #999;
}

.fixed-consumption {
  margin-bottom: 24px;
}

.fixed-consumption-info {
  padding: 16px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.consumption-items {
  margin-bottom: 16px;
}

.consumption-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.consumption-item:last-child {
  border-bottom: none;
}

.consumption-item .item-name {
  flex: 1;
  font-weight: 500;
  color: #333;
}

.consumption-item .item-quantity {
  margin: 0 16px;
  color: #666;
}

.consumption-item .item-price {
  margin: 0 16px;
  color: #1890ff;
}

.consumption-item .item-total {
  font-weight: 600;
  color: #52c41a;
}

.consumption-total {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.total-label {
  font-size: 16px;
  color: #333;
}

.total-amount {
  font-size: 18px;
  font-weight: 600;
  color: #52c41a;
}

.no-fixed-consumption {
  padding: 24px;
  text-align: center;
}

.consumption-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}
</style>
